using System;
using System.Collections.Generic;
using UnityEngine;

namespace Core
{
    [Serializable]
    public abstract class AbstractJsonTable<K, T> : IJsonTable
        where K : IComparable<K>
        where T : class, IJsonTableData<K>
    {
        public virtual string TableName => string.Empty;
        public virtual string SheetName => string.Empty;

        public int Count => list.Count;

        // ReSharper disable once FieldCanBeMadeReadOnly.Local
        // ReSharper disable once CollectionNeverUpdated.Local
        [SerializeField]
        private List<T> list = new();

        protected readonly Dictionary<K, T> dict = new();
        protected readonly HashSet<K> missing = new();

        public T Find(K id)
        {
            if (missing.Contains(id))
            {
                return null;
            }

            if (dict.TryGetValue(id, out var find))
            {
                return find;
            }

            for (var i = 0; i < list.Count; i++)
            {
                var conf = list[i];
                if (conf.Index.CompareTo(id) == 0)
                {
                    dict[id] = conf;
                    // conf.Awake();
                    return conf;
                }
            }

            missing.Add(id);
            return null;
        }
    }
}